<template>
  <div>
    <el-card shadow="never" v-if="welcomeDisplay">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500"> </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px" >
              <div class="px-8px text-right" v-if="useUserStore().grade >= 1">
                <div class="text-14px text-gray-400 mb-20px">{{ t('workplace.guestbook') }}</div>
                <el-link @click="handleGuestbookList()" type="primary">
                  <CountTo
                    class="text-20px"
                    :start-val="0"
                    :end-val="totalSate.guestbook"
                    :duration="2600"
                  />
                </el-link>
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right" >
                <div class="text-14px text-gray-400 mb-20px">{{ t('workplace.toDo') }}</div>
                <el-link @click="handleContentTodoList()" type="primary">
                  <CountTo
                    class="text-20px"
                    :start-val="0"
                    :end-val="totalSate.todo"
                    :duration="2600"
                /></el-link>
              </div>
              <el-divider direction="vertical" border-style="dashed" />
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never" v-if="trendDisplay">
        <template #header>
          <div class="flex justify-between h-3">
            <span>{{ t('cms.access.pv') }}</span>
            <el-link type="primary" :underline="false" @click="handleStatisticTrend()">{{
              t('action.more')
            }}</el-link>

          </div>
        </template>
        <div class="px-3 py-5 mt-3 app-block">
          <div ref="trendChart" class="h-64"></div>
        </div>
      </el-card>

      <el-card shadow="never" class="mt-5px">
        <el-row :gutter="20" justify="space-between" >
          <el-col :xl="10" :lg="10" :md="24" :sm="24" :xs="24" v-if="sourceDisplay">
            <el-card shadow="hover" class="mb-10px">
              <div ref="sourceChart" class="flex p-3 mt-3 justify-evenly app-block h-64"></div>
            </el-card>
          </el-col>
          <el-col :xl="14" :lg="14" :md="24" :sm="24" :xs="24" v-if="visitorDisplay">
            <el-card shadow="hover" class="mb-10px">
              <div class="flex p-3 mt-3 justify-evenly app-block">
                <div class="h-64 w-60 text-primary">
                  <div class="mt-2 text-center">{{ $t('cms.access.visitor.newVisitor') }}</div>
                  <div class="flex items-center justify-center mt-2">
                    <span class="text-3xl">
                      <span v-if="newVisitor.uvCount > 0">{{
                        $n(newVisitor.proportion ?? 0)
                      }}</span>
                      <span v-else>-</span>%
                    </span>
                  </div>
                  <div class="mt-4 space-y-2 text-sm">
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.visitor.pv')
                      }}</el-col>
                      <el-col :span="12">{{ newVisitor.pvCount }}</el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.visitor.uv')
                      }}</el-col>
                      <el-col :span="12">{{ newVisitor.uvCount }}</el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.bounceRate')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="newVisitor.uvCount > 0"
                          >{{ $n((newVisitor.bounceCount * 100) / newVisitor.uvCount) }}%</span
                        >
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.averageDuration')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="newVisitor.uvCount > 0">{{
                          dayjs
                            .duration(
                              Number(newVisitor.accessDuration) / Number(newVisitor.uvCount),
                              'seconds'
                            )
                            .format('HH:mm:ss')
                        }}</span>
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.averagePv')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="newVisitor.uvCount > 0">{{
                          $n(Number(newVisitor.pvCount) / Number(newVisitor.uvCount))
                        }}</span>
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                  </div>
                </div>
                <div class="h-64 w-60 text-gray-secondary">
                  <div class="mt-2 text-center">{{ $t('cms.access.visitor.oldVisitor') }}</div>
                  <div class="flex items-center justify-center mt-2">
                    <span class="text-3xl">
                      <span v-if="oldVisitor.uvCount > 0">{{
                        $n(oldVisitor.proportion ?? 0)
                      }}</span>
                      <span v-else>-</span>%
                    </span>
                  </div>
                  <div class="mt-4 space-y-2 text-sm">
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.visitor.pv')
                      }}</el-col>
                      <el-col :span="12">{{ oldVisitor.pvCount }}</el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.visitor.uv')
                      }}</el-col>
                      <el-col :span="12">{{ oldVisitor.uvCount }}</el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.bounceRate')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="oldVisitor.uvCount > 0"
                          >{{ $n((oldVisitor.bounceCount * 100) / oldVisitor.uvCount) }}%</span
                        >
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.averageDuration')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="newVisitor.uvCount > 0">{{
                          dayjs
                            .duration(oldVisitor.accessDuration / oldVisitor.uvCount, 'seconds')
                            .format('HH:mm:ss')
                        }}</span>
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                    <el-row :gutter="24">
                      <el-col :span="12" class="text-right">{{
                        $t('cms.access.averagePv')
                      }}</el-col>
                      <el-col :span="12">
                        <span v-if="oldVisitor.uvCount > 0">{{
                          $n(oldVisitor.pvCount / oldVisitor.uvCount)
                        }}</span>
                        <span v-else>-</span>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-10px" v-if="noticeDisplay">
      <el-card shadow="never" class="mt-0px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.notice') }}</span>
            <el-link type="primary" :underline="false" @click="handleMessageList()">{{
              t('action.more')
            }}</el-link>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <div v-for="(item, index) in notice" :key="`dynamics-${index}`">
            <div class="flex items-center">
              <div>
                <div class="text-14px ml-2">
                  <el-link type="primary" @click="openNoticeDialog(item.id)">{{
                    item.title
                  }}</el-link>
                </div>
                <div class="mt-15px text-12px text-gray-400">
                  {{ formatTime(item.createTime, 'yyyy-MM-dd') }}
                </div>
              </div>
            </div>
            <el-divider />
          </div>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>

  <!--强制修改密码对话框-->
  <ResetPwdDialog ref="passwordFormRef" />
  <!-- 通知公告查看详情弹窗 -->
  <NoticeDialog ref="noticeRef" />
</template>
<script lang="ts" setup>
import { formatTime } from '@/utils'
import ResetPwdDialog from '@/views/Profile/components/ResetPwdDialog.vue'
import NoticeDialog from './NoticeDialog.vue'
import { useUserStore } from '@/store/modules/user'
import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import * as UserApi from '@/api/system/user'
import * as ContentApi from '@/api/cms/content'
import * as GuestbookApi from '@/api/cms/guestbook'
import * as NoticeApi from '@/api/system/notice'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import echarts, { ECOption } from '@/plugins/echarts'
import { getTrendStat, getSourceTypeStat, getVisitorStat } from '@/api/cms/flowstatistic'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { push } = useRouter() // 路由

const { t } = useI18n()
dayjs.extend(duration)

defineOptions({ name: 'Home' })
const message = useMessage() // 消息弹窗
const userStore = useUserStore()
const { setWatermark } = useWatermark()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  guestbook: 0,
  todo: 0
})
const noticeRef = ref()
const openNoticeDialog = (id: number) => {
  noticeRef.value.open('detail', id)
}
const passwordFormRef = ref()
const openPasswordForm = () => {
  passwordFormRef.value.open()
}

const getCount = async () => {
  totalSate.guestbook = await GuestbookApi.getGuestbookToReply()
  totalSate.todo = await ContentApi.getToAuditContentApi()
}
// 获取通知公告
let notice = reactive<Notice[]>([])
const noticeReqPageVO = {
  status: 0,
  pageSize: 6
}
const getNotice = async () => {
  const data = await NoticeApi.getNoticePage(noticeReqPageVO)
  notice = Object.assign(notice, data.list)
}

const trendChart = shallowRef<HTMLElement>()
const initTrendChart = async () => {
  const list = await getTrendStat({
    begin: dayjs().startOf('day').subtract(1, 'day').format(),
    end: dayjs().endOf('day').format()
  })
  const option: ECOption = {
    tooltip: { trigger: 'axis' },
    legend: { data: [t('cms.access.trend.yesterdayPv'), t('cms.access.trend.todayPv')] },
    grid: { left: 16, right: 16, top: 40, bottom: 0, containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisTick: { show: false },
      data: Array.from(Array(24).keys())
    },
    yAxis: { type: 'value', minInterval: 1 },
    series: [
      {
        name: t('cms.access.trend.yesterdayPv'),
        type: 'line',
        symbol: 'circle',
        color: '#a0cfff',
        data: list
          .filter((item) => dayjs(item.date) < dayjs().startOf('day'))
          .map((item) => Number(item.pvCount))
      },
      {
        name: t('cms.access.trend.todayPv'),
        type: 'line',
        symbol: 'circle',
        color: '#409eff',
        areaStyle: { color: '#ecf5ff' },
        data: list
          .filter((item) => dayjs(item.date) >= dayjs().startOf('day'))
          .map((item) => Number(item.pvCount))
      }
    ]
  }
  const chartDom = trendChart.value
  if (chartDom == null) {
    return
  }
  let chart = echarts.getInstanceByDom(chartDom)
  if (chart == null) {
    chart = echarts.init(chartDom)
  }
  chart.setOption(option)
  window.addEventListener('resize', function () {
    chart && chart.resize()
  })
}

const sourceChart = shallowRef<HTMLElement>()
const initSourceTypeChart = async () => {
  const list = await getSourceTypeStat({
    begin: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
    end: dayjs().format('YYYY-MM-DD')
  })
  const total = list.reduce((acc, curr) => acc + curr.pvCount, 0)
  const option: ECOption = {
    title: {
      text: t('cms.access.source.name'),
      textStyle: { color: '#909399', fontWeight: 'normal', fontSize: 16 }
    },
    tooltip: {
      trigger: 'item',
      valueFormatter: (value: any) => Number(Number(value * 100) / total).toFixed(2) + '%'
    },
    legend: { type: 'scroll', orient: 'vertical', right: '10%', top: 16, bottom: 16 },
    series: [
      {
        name: t('cms.access.source.name'),
        type: 'pie',
        radius: '72%',
        center: ['40%', '56%'],
        data: list.map((item) => ({
          value: Number(item.pvCount),
          name: t(`cms.access.source.${item.statName}`)
        }))
      }
    ]
  }
  const sourceTypeChartDom = sourceChart.value
  if (sourceTypeChartDom == null) {
    return
  }
  let sourceTypeChart = echarts.getInstanceByDom(sourceTypeChartDom)
  if (sourceTypeChart == null) {
    sourceTypeChart = echarts.init(sourceTypeChartDom)
  }
  sourceTypeChart.setOption(option)
  window.addEventListener('resize', function () {
    sourceTypeChart && sourceTypeChart.resize()
  })
}

const newVisitor = ref<any>({})
const oldVisitor = ref<any>({})
const fetchVisitorStat = async () => {
  const visitorStat = await getVisitorStat({
    begin: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
    end: dayjs().format('YYYY-MM-DD')
  })
  newVisitor.value = visitorStat['newVisitor']
  oldVisitor.value = visitorStat['oldVisitor']
  const totalUvCount = newVisitor.value.uvCount + oldVisitor.value.uvCount
  if (totalUvCount > 0) {
    newVisitor.value.proportion = (newVisitor.value.uvCount * 100) / totalUvCount
    oldVisitor.value.proportion = (oldVisitor.value.uvCount * 100) / totalUvCount
  } else {
    newVisitor.value.proportion = 50
    oldVisitor.value.proportion = 50
  }
}
/** 跳转到趋势统计列表 */
const handleStatisticTrend = () => {
 push({
   path: '/statistic/access/trend'
 })
}
//通知公告列表跳转
const handleMessageList = () => {
 push({
  path: '/system/messages/notice'
 })
}
const handleGuestbookList = () => {
 push({
   path: '/interact/guestbook'
 })
}
const handleContentTodoList = () => {
 push({
  path: '/cms/content/content/manager/todo'
 })
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getNotice(),
    initTrendChart(),
    initSourceTypeChart(),
    fetchVisitorStat()
  ])
  loading.value = false
}

getAllApi()
/** 初始化 */
onMounted(async () => {
  //检查是否需要强制修改密码，如果是则打开修改密码弹窗
  const needChangePwd = await UserApi.getNeedChangePwd()
  if (needChangePwd) {
    openPasswordForm()
  }
  //检查密码过期警告天数,到达则弹窗警告
  const notifyChangePwd = await UserApi.getNotifyChangePwd()
  //已经过期0 则无需警告
  if (notifyChangePwd > 0) {
    message.notify('密码即将过期，请修改密码,剩余天数 ' + notifyChangePwd)
  }
})
const { wsCache } = useCache()
const userInfo = wsCache.get(CACHE_KEY.USER)
const trendDisplay = ref(true);
const noticeDisplay = ref(true);
const sourceDisplay = ref(true);
const visitorDisplay = ref(true);
const welcomeDisplay = ref(true);
const workbenchs = userInfo.workbenchs
if(workbenchs&&workbenchs.length>0) {
  welcomeDisplay.value = workbenchs.filter(w=>w.blockCode=="welcome")[0].display
  trendDisplay.value = workbenchs.filter(w=>w.blockCode=="trend")[0].display
  noticeDisplay.value = workbenchs.filter(w=>w.blockCode=="notice")[0].display
  sourceDisplay.value = workbenchs.filter(w=>w.blockCode=="source")[0].display
  visitorDisplay.value = workbenchs.filter(w=>w.blockCode=="visitor")[0].display
}

</script>
